import AxIos from 'axios'
import {localStorage as storage} from 'lsy-storages'
import {Message} from 'view-design'
import lodash from 'lodash'

const baseUrl = 'http://127.0.0.1:18306/'
const debug = true

export default function (options, urlType = 'base') {
  let defaultOptions = {}

  if (urlType === 'base') {
    defaultOptions = {
      method: 'get',
      baseURL: baseUrl,
      headers: {
        accept: 'application/json',
        client: 'manage',
        auth: storage.getItem('auth')
      }
    }
  }

  if (urlType === 'service') {
    defaultOptions.baseURL = baseUrl
  }

  if (options.hasOwnProperty('cache') && debug === false) {
    let cache = storage.getItem(options.cache)

    if (cache) {
      return new Promise(function (resolve) {
        resolve(cache)
      })
    }
  }
  if (options.hasOwnProperty('headers')) {
    options.headers = Object.assign(defaultOptions.headers, options.headers)
  }

  let success
  if (options.hasOwnProperty('success')) {
    success = options.success
    delete options.success
  }

  let error
  if (options.hasOwnProperty('error')) {
    error = options.error
    delete options.error
  }


  options = Object.assign(defaultOptions, options)
  let method = lodash.toLower(options.method)
  // 跨域
  //options.withCredentials = true

  AxIos(options).then(response => {
    if (options.hasOwnProperty('cache')) {
      storage.setItem(options.cache, {
        data: response.data
      })
    }

    if (method !== 'get' && lodash.isFunction(success)) {
      success(response)
    } else if (method !== 'get') {
      Message.success(response.data.msg)
    }
  }).catch(e => {
    if (method !== 'get' && lodash.isFunction(error)) {
      error(e)
    } else if (method !== 'get') {
      Message.error(e.response)
    }
  })
}